public class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;

        int[][] f = new int[len][3];
        int[][] g = new int[len][3];

        for (int j = 0; j < 3; j++) {
            f[0][j] = 0x3f3f3f3f * (-1);//防止int越界
            g[0][j] = 0x3f3f3f3f * (-1);
        }

        f[0][0] = prices[0] * (-1);
        g[0][0] = 0;

        for (int i = 1; i < len; i++) {
            for (int j = 0; j < 3; j++) {
                f[i][j] = Math.max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j - 1 >= 0) {
                    g[i][j] = Math.max(g[i][j], f[i - 1][j - 1] + prices[i]);
                }
            }
        }

        int ret = 0;

        for (int num : g[len - 1]) {
            ret = Math.max(ret, num);
        }
        return ret;
    }
}
